<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="商品名称" prop="goodsName">
        <el-input v-model="queryParams.goodsName" placeholder="请输入" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="商品分类" prop="goodsCategoryId">
        <el-tree-select style="width: 100%" clearable v-model="queryParams.goodsCategoryId" :data="categoryOptions"
          :props="{
      value: 'id',
      label: 'categoryName',
      children: 'children',
    }" value-key="id" placeholder="请选择" check-strictly @change="handleQuery" />
      </el-form-item>
      <el-form-item label="上架状态" prop="tag">
        <el-select v-model="queryParams.status" placeholder="请选择" clearable style="width: 100%" @change="handleQuery">
          <el-option v-for="dict in goods_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" dark @click="handleAdd"
          v-hasPermi="['goods:goods:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['goods:goods:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['goods:goods:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['goods:goods:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="goodsList">
      <el-table-column label="商品名称" align="center" prop="goodsName" />
      <el-table-column label="商品简介" align="center" prop="goodsIntro" />
      <el-table-column label="商品分类" align="center" prop="goodsCategoryName" />
      <el-table-column label="商品图片" align="center" prop="goodsCoverImg">
        <template #default="scope">
          <ImagePreview :src="scope.row.goodsCoverImg" :height="40" :width="40"></ImagePreview>
        </template>
      </el-table-column>
      <el-table-column label="商品售价" align="center" prop="sellingPrice" />
      <el-table-column label="商品库存数量" align="center" prop="stockNum" />
      <el-table-column label="上架状态" align="center" prop="status">
        <template #default="scope">
          <span v-if="scope.row.status === '0'">下架</span>
          <span v-if="scope.row.status === '1'">上架</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['goods:goods:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['goods:goods:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page.sync="queryParams.pageNum"
      v-model:limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改商品对话框 -->
    <el-dialog :title="title" v-model="open" width="1100px" append-to-body>
      <el-form ref="goodsRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="商品规格" prop="specsFlag">
          <el-radio-group v-model="form.specsFlag" @change="handleSpecsChange">
            <el-radio v-for="dict in specs_dict" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品名称" prop="goodsName">
          <el-input v-model="form.goodsName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品简介" prop="goodsIntro">
          <el-input v-model="form.goodsIntro" placeholder="请输入商品简介" />
        </el-form-item>
        <el-form-item label="商品分类" prop="goodsCategoryId">
          <el-tree-select style="width: 100%" v-model="form.goodsCategoryId" :data="categoryOptions" :props="{
      value: 'id',
      label: 'categoryName',
      children: 'children',
    }" value-key="id" placeholder="请选择" check-strictly />
        </el-form-item>
        <el-form-item label="商品主图" prop="goodsCoverImg">
          <image-upload title="商品主图" v-model="form.goodsCoverImg" :limit="1" />
        </el-form-item>

        <el-form-item label="商品多规格" prop="specsList" v-if="form.specsFlag === '1'">
          <el-table :data="form.specsList" style="margin-top: 8px">
            <el-table-column prop="specsName" label="名称" width="200" align="center">
              <template #default="scope">
                <el-input v-model="scope.row.specsName" placeholder="请输入" />
              </template>
            </el-table-column>
            <el-table-column prop="specsPrice" label="价格" width="200" align="center">
              <template #default="scope">
                <el-input-number v-model="scope.row.specsPrice" :min="0" placeholder="请输入" />
              </template>
            </el-table-column>
            <el-table-column prop="specsOriginPrice" label="原价" width="200" align="center">
              <template #default="scope">
                <el-input-number v-model="scope.row.specsOriginPrice" :min="0" placeholder="请输入" />
              </template>
            </el-table-column>
            <el-table-column prop="specsStockNum" label="库存数量" width="200" align="center">
              <template #default="scope">
                <el-input-number v-model="scope.row.specsStockNum" :min="1" placeholder="请输入" />
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-button link type="primary" icon="Delete" @click="handleSpecsDelete(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button type="primary" @click="handleSpecsAdd">添加一行</el-button>
        </el-form-item>

        <el-form-item label="商品原价" prop="originalPrice" v-if="form.specsFlag === '0'">
          <el-input-number v-model="form.originalPrice" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="商品售价" prop="sellingPrice" v-if="form.specsFlag === '0'">
          <el-input-number v-model="form.sellingPrice" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="商品库存数量" prop="stockNum" v-if="form.specsFlag === '0'">
          <el-input-number v-model="form.stockNum" controls-position="right" :min="0" />
        </el-form-item>

        <el-form-item label="商品标签" prop="tag">
          <el-input v-model="form.tag" placeholder="请输入商品标签" />
        </el-form-item>

        <el-form-item label="商品轮播图" prop="goodsCarousel">
          <image-upload title="商品轮播图" v-model="form.goodsCarousel" :limit="20" />
        </el-form-item>
        <el-form-item label="商品详情" v-if="richTextShow">
          <editor v-model="form.goodsDetailContent" :min-height="192" />
        </el-form-item>

        <el-form-item label="上架状态" prop="status">
          <el-select v-model="form.status" placeholder="上架状态" clearable style="width: 100%" @change="handleQuery">
            <el-option v-for="dict in goods_status" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否添加课程" prop="needCourseFlag">
          <el-radio-group v-model="form.needCourseFlag">
            <el-radio v-for="dict in need_course_flag_dict" :key="dict.value" :label="dict.value">{{ dict.label
              }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序号" prop="sortNum">
          <el-input-number v-model="form.sortNum" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Goods">
import {
  listGoods,
  getGoods,
  delGoods,
  addGoods,
  updateGoods,
} from "@/api/goods/goods";

import { listCategory } from "@/api/goods/goodsCategory";

const { proxy } = getCurrentInstance();

// 遮罩层
const loading = ref(true);
// 选中数组
const ids = ref([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 商品表格数据
const goodsList = ref([]);
// 弹出层标题
const title = ref("");
// 是否显示弹出层
const open = ref(false);
// 是否显示富文本
const richTextShow = ref(false);
// 商品分类树数据
const categoryOptions = ref([]);
// 上下架状态
const goods_status = ref([
  {
    value: "0",
    label: "下架",
  },
  {
    value: "1",
    label: "上架",
  },
]);

// 是否添加课程信息
const need_course_flag_dict = ref([
  {
    value: "0",
    label: "否",
  },
  {
    value: "1",
    label: "是",
  },
]);

const specs_dict = ref([
  {
    value: "0",
    label: "单规格",
  },
  {
    value: "1",
    label: "多规格",
  },
]);

const checkSpecsList = (rule, value, callback) => {
  if (form.value.specsFlag === '1') {
    if (form.value.specsList.length === 0) {
      return callback(new Error("多规格不能为空"));
    }

    const specsMap = {}
    for (let i = 0; i < form.value.specsList.length; i++) {
      const specsItem = form.value.specsList[i]
      if (!specsItem.specsName) {
        return callback(new Error("规格名称不能为空"));
      }
      if (specsMap.hasOwnProperty(specsItem.specsName)) {
        return callback(new Error("规格名称不能重复"));
      }
      if (!specsItem.specsPrice) {
        return callback(new Error("单价不能为空或不能等于0"));
      }
      if (!specsItem.specsOriginPrice) {
        return callback(new Error("原价不能为空或不能等于0"));
      }
      if (!specsItem.specsStockNum) {
        return callback(new Error("库存数量不能为空或不能等于0"));
      }
      specsMap[specsItem.specsName] = specsItem.specsName
    }

  }
  callback();
};


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    goodsName: null,
    goodsCategoryId: null,
    status: null,
  },
  rules: {
    goodsName: [{ required: true, message: "商品名不能为空", trigger: "blur" }],
    goodsIntro: [
      { required: true, message: "商品简介不能为空", trigger: "blur" },
    ],
    goodsCategoryId: [
      { required: true, message: "关联分类id不能为空", trigger: "blur" },
    ],
    goodsCoverImg: [
      { required: true, message: "商品主图不能为空", trigger: "blur" },
    ],
    goodsCarousel: [
      { required: true, message: "商品轮播图不能为空", trigger: "blur" },
    ],
    goodsDetailContent: [
      { required: true, message: "商品详情不能为空", trigger: "blur" },
    ],
    originalPrice: [
      { required: true, message: "商品价格不能为空", trigger: "blur" },
    ],
    sellingPrice: [
      { required: true, message: "商品实际售价不能为空", trigger: "blur" },
    ],
    stockNum: [
      { required: true, message: "商品库存数量不能为空", trigger: "blur" },
    ],
    specsList: [{
      required: true, validator: checkSpecsList, trigger: "blur"
    }],
    tag: [{ required: true, message: "商品标签不能为空", trigger: "blur" }],
    status: [
      {
        required: true,
        message: "商品上架状态 0-下架 1-上架不能为空",
        trigger: "change",
      },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询商品列表 */
const getList = () => {
  loading.value = true;
  listGoods(queryParams.value).then((response) => {
    goodsList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
};

/** 查询分类下拉树结构 */
function getCategoryTree() {
  categoryOptions.value = [];
  listCategory().then((response) => {
    const tree = proxy.handleTree(response.data, "id");
    categoryOptions.value = tree;
  });
}

// 取消按钮
const cancel = () => {
  richTextShow.value = false;
  open.value = false;
  reset();
};
// 表单重置
const reset = () => {
  form.value = {
    id: null,
    goodsName: null,
    goodsIntro: null,
    goodsCategoryId: null,
    goodsCoverImg: null,
    goodsCarousel: null,
    goodsDetailContent: null,
    originalPrice: null,
    sellingPrice: null,
    stockNum: null,
    tag: null,
    status: "1",
    needCourseFlag: "0",
    sortNum: 1,
    createBy: null,
    createId: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
    specs: "0",
    specsList: []
  };
  proxy.resetForm("goodsRef");
};
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  resetForm("queryForm");
  handleQuery();
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  richTextShow.value = true;
  form.value.specsList = []
  open.value = true;
  title.value = "添加商品";
};
/** 修改按钮操作 */
const handleUpdate = (row) => {
  reset();
  richTextShow.value = true;
  const id = row.id || ids.value;
  getGoods(id).then((response) => {
    form.value = response.data;
    if(!form.value.specsList) {
      form.value.specsList = []
    }
    open.value = true;
    title.value = "修改商品";
  });
};
/** 提交按钮 */
const submitForm = () => {
  proxy.$refs["goodsRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateGoods(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addGoods(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
};
/** 删除按钮操作 */
const handleDelete = (row) => {
  const ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除商品编号为"' + ids + '"的数据项？')
    .then(function () {
      return delGoods(ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
};
/** 导出按钮操作 */
const handleExport = () => {
  proxy.download(
    "goods/goods/export",
    {
      ...queryParams.value,
    },
    `goods_${new Date().getTime()}.xlsx`
  );
};

getList();

getCategoryTree();


/**多规格 */
const handleSpecsChange = (val) => {
  form.value.originalPrice = 0;
  form.value.sellingPrice = 0;
  form.value.stockNum = 1;
  if (val === '1') {
    form.value.specsList = [{
      specsName: '',
      specsPrice: 0,
      specsOriginPrice: 0,
      specsStockNum: 1
    }]
  } else {
    form.value.specsList = []
  }

}

const handleSpecsAdd = () => {
  form.value.specsList.push({
    specsName: '',
    specsPrice: 0,
    specsOriginPrice: 0,
    specsStockNum: 1
  })
}

const handleSpecsDelete = (index) => {
  form.value.specsList.splice(index, 1);
}

</script>
